package com.qi.demo01.Demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zjq
 * @date 2020/3/25 15:29
 */
public class Demo02 {
    public static void main(String[] args) {
        //并发，多个线程操作一个资源类，把资源类丢入线程
        Ticket2 ticket = new Ticket2();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) ticket.sale();
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        }, "C").start();

    }
}

/**
 * Lock三步曲
 * 1.new ReentrantLock()
 * 2.lock.lock();//加锁
 * 3.finally->lock.unlock();//解锁
 */

class Ticket2 {
    Lock lock = new ReentrantLock();
    //属性，方法
    private int number = 30;
    //买票的方式

    public void sale() {

        lock.lock();//加锁
        try {//业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票，剩余" + number);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }


    }

}